package com.springsummer.information.green.beans;



import com.springsummer.information.green.annotation.AutoValue;

import java.util.Collection;
import java.util.logging.Logger;

public class AutowiredAnnotationBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware, EnvironmentAware {

    private static final Logger logger = Logger.getLogger(AutowiredAnnotationBeanPostProcessor.class.getName());

    //private BeanFactory beanFactory;

    private ConfigurableListableBeanFactory beanFactory;

    private Environment environment;


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws Exception {
        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
    }

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment=environment;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
        logger.info("AutowiredAnnotationBeanPostProcessor postProcessBeforeInitialization beanname:" + beanName);
        InjectionMetadata injectionMetadataService = new InjectionMetadata();
        InjectionMetadata autowiringMetadatas = injectionMetadataService.findAutowiringMetadata(beanName, bean.getClass());
        Collection<InjectionElement> injectionElements = autowiringMetadatas.getInjectionElements();
        for (InjectionElement element : injectionElements) {

            String memberName = element.getMemberName();
            if(element.autowireBeanFlag()){
                Object memberValue = getBeanFactory().getBean(memberName);
                element.inject(bean, beanName, memberValue);
            }
            processValueAnnotation(bean, beanName, element);

            logger.info("autowireing membername:" + memberName + " for bean:" + beanName);
        }

        return bean;
    }

    private String processValueAnnotation(Object bean, String beanName, InjectionElement element) throws Exception {
        if(element==null){
            return "0";
        }
        if(element.autowireValueFlag()){
            AutoValue autoValueMeta= element.getAutoValueMeta();
            String propKey=autoValueMeta.value();
            Object propValue=null;
            if(propKey.startsWith("${")){
                propValue="";
                if(environment!=null){
                    propValue=environment.getProperty(propKey,"");
                }
            }else {
                //set value val
                propValue=propKey;
            }

            element.inject(bean, beanName, propValue);
        }
        return "1";
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
        return bean;
    }

}
